<template>
  <a-card title="产品列表">
    <div class="table-page-search-wrapper">
      <a-table
        :dataSource="dataSource"
        :columns="columns"
        bordered
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'index'">
            {{ index + 1 }}
          </template>
          <template v-else-if="column.key === 'updateTime'">
            {{ $dayjs(record.updateTime).format("YYYY-MM-DD HH:mm") }}
          </template>
          <template v-else-if="column.key === 'img'">
            <a-image v-if="record.img" :src="record.img" :width="88" />
          </template>
          <template v-else-if="column.key === 'action'">
            <a @click="handelEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handelDelete(record)" style="color: red">删除</a>
          </template>
        </template>
      </a-table>
    </div>
  </a-card>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from "vue";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";
import { productList, productDelete } from "@/api/product";
const { appContext } = getCurrentInstance();
const { $dayjs } = appContext.config.globalProperties;
const router = useRouter();
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  onChange: (current) => {
    pagination.value.current = current;
    getList();
  },
});
const columns = [
  {
    title: "序号",
    dataIndex: "index",
    key: "index",
  },
  {
    title: "产品名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "简介",
    dataIndex: "desc",
    key: "desc",
  },
  {
    title: "封面",
    dataIndex: "img",
    key: "img",
  },
  {
    title: "修改日期",
    dataIndex: "updateTime",
    key: "updateTime",
  },
  {
    title: "操作",
    key: "action",
  },
];

const dataSource = ref([]);

const getList = async () => {
  const { msg, success, data } = await productList({
    page: pagination.value.current,
    pageSize: pagination.value.pageSize,
  });
  if (success) {
    message.success(msg);
    dataSource.value = data.row || [];
    pagination.value.total = data.count;
  } else {
    message.error(msg);
  }
};

// 删除操作
const handelDelete = async (row) => {
  const { _id } = row;
  const { msg, success } = await productDelete({
    _id,
  });
  if (success) {
    message.success(msg);
    getList();
  } else {
    message.error(msg);
  }
};
// 编辑操作
const handelEdit = async (row) => {
  const { _id } = row;
  console.log(row);
  router.push({
    path: "/product-manage/add",
    query: {
      id: _id,
    },
  });
};

onMounted(() => {
  getList();
});
</script>


<style lang="scss" scoped>
</style>